package com.forlove.app.qselect.index.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.NetworkUtils;
import com.forlove.app.common.utils.ParseHelper;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.utils.SystemUtils;
import com.forlove.app.common.widget.recyview.BaseRecyclerAdapter;
import com.forlove.app.manager.ContactsManager;
import com.forlove.app.manager.FriendManager;
import com.forlove.app.manager.async.LoadContactsAsync;
import com.forlove.app.qselect.CommonEntity;
import com.forlove.app.qselect.MainActivity;
import com.forlove.app.qselect.friend.entity.FriendEntity;
import com.forlove.app.qselect.friend.entity.MineFriendEntity;
import com.forlove.app.qselect.index.adapter.CustomCandidateAdapter;
import com.forlove.app.qselect.index.presenter.CustomCandidatePresenter;
import com.forlove.app.qselect.index.view.CustomCandidateView;
import com.forlove.app.qselect.login.entity.ContactsInfoEntity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by yinzhiqiang on 2017/11/8.
 * 自定义候选人
 */

@RuntimePermissions
public class CustomCandidateActivity extends BaseActivity<CustomCandidatePresenter> implements CustomCandidateView,
        LoaderManager.LoaderCallbacks<List<ContactsInfoEntity>>, View.OnClickListener {

    @BindView(R.id.recycler_candidate)
    RecyclerView recyCandidate;

    @BindView(R.id.choose_num)
    TextView chooseNum;

    @BindView(R.id.confirm_candidate)
    TextView confirm_candidate;

    @BindView(R.id.view_fade_back)
    FrameLayout fadeBack;

    @BindView(R.id.view_no_friend)
    RelativeLayout view_no_friend;

    @BindView(R.id.tool_view)
    RelativeLayout toolsView;  //toolbar view

    @BindView(R.id.image_search)
    ImageView image_search;  //搜索图标

    @BindView(R.id.view_search)
    RelativeLayout view_search; //搜索框

    @BindView(R.id.edittext_input_query)
    AppCompatEditText edittext_input_query; //输入搜索内容

    @BindView(R.id.text_cancel_query)
    AppCompatTextView text_cancel_query; //取消


    private CustomCandidateAdapter customCandidateAdapter;
    private List<MineFriendEntity> recomendFriend = new ArrayList<>();//设置了的候选人
    private List<MineFriendEntity> qyqFriend = new ArrayList<>();//圈一圈好友
    private List<ContactsInfoEntity> contactsInfoEntities = new ArrayList<>();//通讯录好友
    private List<MineFriendEntity> friendEntities = new ArrayList<>();//合并后的所友好友
    private List<MineFriendEntity> selectFriend = new ArrayList<>();//合并后的选择的好友
    private boolean recommendFlag = false;//获取到推荐好友，答题接口返回
    private boolean qyqFriendFlag = false;//获取到圈一圈好友的标志
    private boolean contactsFlag = false;//获取到通讯录好友标记
    private LoadContactsAsync loadContactsAsync;
    private String quryStr;//搜索条件
    private List<MineFriendEntity> queryFriend = new ArrayList<>();//搜索结果的firend
    private Handler dataHandler;
    private HandlerThread handlerThread;
    private Handler friendHandler;

    @Override
    public int getLayoutId() {
        return R.layout.activity_custom_candidate;
    }

    @NeedsPermission(Manifest.permission.READ_CONTACTS)
    void needContacts() {
        getSupportLoaderManager().restartLoader(LoadContactsAsync.ASYNC_ID, null, this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        CustomCandidateActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnPermissionDenied(Manifest.permission.READ_CONTACTS)
    void getContactsDenied() {
        Toast.makeText(this, "通讯录权限被拒绝", Toast.LENGTH_SHORT).show();
        contactsFlag = true;
    }

    @OnNeverAskAgain(Manifest.permission.READ_CONTACTS)
    void refuseAuthorContacts() {
        Toast.makeText(this, "通讯录权限被拒绝", Toast.LENGTH_SHORT).show();
        contactsFlag = true;
    }

    @Override
    public void initView() {
        fadeBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        if (presenter == null) {
            presenter = new CustomCandidatePresenter(this);
        }
        confirm_candidate.setOnClickListener(this);
        //加载通讯录数据
        if (!NetworkUtils.instance(this).isNetworkAvailable()) {
            Toast.makeText(this, "请检查网络！", Toast.LENGTH_SHORT).show();
        }
        initData();
        initSerarchView();
        loadFriendCache();
        presenter.requestCandidateList();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        StatusBarCompat.compat(this, Color.parseColor("#ffffff"));
    }

    private void loadFriendCache() {
        if (dataHandler == null) {
            dataHandler = new Handler(getMainLooper(), new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    if (msg.what == 10086) {
                        updateData();
                    }
                    return false;
                }
            });
        }
        if (handlerThread == null) {
            handlerThread = new HandlerThread("loadLocalFriend");
            handlerThread.start();
        }
        if (friendHandler == null) {
            friendHandler = new Handler(handlerThread.getLooper());
        }
        friendHandler.post(new Runnable() {
            @Override
            public void run() {
                if (contactsInfoEntities.size() == 0) {
                    contactsInfoEntities.clear();
                    contactsInfoEntities.addAll(ContactsManager.getContectInfo(CustomCandidateActivity.this));
                    if (contactsInfoEntities.size() > 0) {
                        contactsFlag = true;
                        loadFriends();
                    } else {
                        CustomCandidateActivityPermissionsDispatcher.needContactsWithPermissionCheck(CustomCandidateActivity.this);
                    }
                }
                if (qyqFriend.size() <= 0) {
                    String friendList = FriendManager.getFriendList(CustomCandidateActivity.this);
                    try {
                        if (StringUtils.isNotEmpty(friendList)) {
                            List<MineFriendEntity> friends =
                                    ParseHelper.getModelList(friendList, "data.friends", FriendEntity.class);
                            List<MineFriendEntity> contacts =
                                    ParseHelper.getModelList(friendList, "data.concats", FriendEntity.class);
                            List<MineFriendEntity> entities = FriendManager.mergeFriends(friends, contacts, -1);
                            if (entities.size() > 0) {
                                qyqFriend.addAll(entities);
                                qyqFriendFlag = true;
                                loadFriends();
                            }
                        }
                        if (qyqFriend.size() == 0 || !qyqFriendFlag) {
                            presenter.requestFriends();
                        }
                    } catch (Exception e) {
                    }
                }
            }
        });


    }

    private void initSerarchView() {
        image_search.setOnClickListener(this);
        text_cancel_query.setOnClickListener(this);
        edittext_input_query.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                quryStr = s.toString().replaceAll(" ", "");
                queryFriend.clear();
                queryFriend.addAll(getLocalSearchFriend(quryStr));
                if (StringUtils.isNotEmpty(quryStr)) {
                    customCandidateAdapter.setQueryStr(quryStr);
                    customCandidateAdapter.updateDatas(queryFriend);
                } else {
                    List<MineFriendEntity> list = new ArrayList<>();
                    list.addAll(friendEntities);
                    friendEntities.clear();
                    customCandidateAdapter.setQueryStr("");
                    friendEntities.addAll(FriendManager.sortRecommend(list));
                    customCandidateAdapter.updateDatas(friendEntities);
                }
            }
        });
    }

    private List<MineFriendEntity> getLocalSearchFriend(String queryStr) {

        List<MineFriendEntity> local = new ArrayList<>();
        for (MineFriendEntity friendEntity : friendEntities) {
            if (StringUtils.isNotEmpty(queryStr) &&
                    ((StringUtils.isNotEmpty(friendEntity.getAvaliableName()) && friendEntity.getAvaliableName().contains(queryStr))
                            || (StringUtils.isNotEmpty(friendEntity.mobile) && friendEntity.mobile.contains(queryStr))
                            || (StringUtils.isNotEmpty(friendEntity.contactsNumber) && friendEntity.contactsNumber.contains(queryStr))
                            || (StringUtils.isNotEmpty(friendEntity.contactsName) && friendEntity.contactsName.contains(queryStr))
                    )) {
                local.add(friendEntity);
            }
        }
        return local;
    }

    private void cancelQuery() {
        quryStr = "";
        if (queryFriend != null) {
            queryFriend.clear();
        }
        customCandidateAdapter.setQueryStr(quryStr);
        edittext_input_query.setText("");
        SystemUtils.hideKeyBoard(this, text_cancel_query);
    }

    private LoadContactsAsync createContacts() {
        if (loadContactsAsync == null) {
            loadContactsAsync = new LoadContactsAsync(this);
        }
        return loadContactsAsync;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    protected void onDestroy() {
        cancelQuery();
        getSupportLoaderManager().destroyLoader(LoadContactsAsync.ASYNC_ID);
        if (handlerThread != null) {
            handlerThread.quitSafely();
            handlerThread = null;
        }
        if (friendHandler != null) {
            friendHandler.removeCallbacksAndMessages(null);
            friendHandler = null;
        }
        if (dataHandler != null) {
            dataHandler.removeCallbacksAndMessages(null);
            dataHandler = null;
        }
        customCandidateAdapter = null;
        super.onDestroy();
    }

    public void initData() {
        customCandidateAdapter = new CustomCandidateAdapter(this, R.layout.item_add_friends, friendEntities, presenter);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        recyCandidate.setLayoutManager(gridLayoutManager);
        recyCandidate.setAdapter(customCandidateAdapter);
        customCandidateAdapter.hideFooterView();
        customCandidateAdapter.hideEmptyView();
        customCandidateAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                MineFriendEntity mineFriendEntity;
                if (StringUtils.isNotEmpty(quryStr) && queryFriend.size() > position) {
                    mineFriendEntity = queryFriend.get(position);
                } else {
                    mineFriendEntity = friendEntities.get(position);
                }
                if (mineFriendEntity.isRecomend) {
                    mineFriendEntity.isRecomend = false;
                    selectFriend.remove(mineFriendEntity);
                } else {
                    mineFriendEntity.isRecomend = true;
                    selectFriend.add(mineFriendEntity);
                }
                customCandidateAdapter.notifyItemChanged(position);
                chooseNum.setText(selectFriend.size() + "/" + friendEntities.size());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    private synchronized void loadFriends() {
        if (contactsFlag && recommendFlag && qyqFriendFlag) {
            if (handlerThread == null) {
                handlerThread = new HandlerThread("loadLocalFriend");
                handlerThread.start();
            }
            if (friendHandler == null) {
                friendHandler = new Handler(handlerThread.getLooper());
            }

            friendHandler.post(new Runnable() {
                @Override
                public void run() {
                    List<MineFriendEntity> recommends = new ArrayList<>();
                    recommends.addAll(recomendFriend);
//                    LogUtil.e("yjl", "recommends:" + recommends.size()
//                            + "  qyqFriend:" + qyqFriend.size() + "   contactsInfoEntities:" + contactsInfoEntities.size());
                    List<MineFriendEntity> candidateFriend = FriendManager.getSubjectCandidate(recommends, qyqFriend, contactsInfoEntities, -1);
//                    LogUtil.e("yjl", "sortFriend:" + candidateFriend.size());
                    friendEntities.clear();
                    friendEntities.addAll(FriendManager.sortRegisterFriend(candidateFriend));
                    if (dataHandler != null) {
                        dataHandler.sendEmptyMessage(10086);
                    }
                }
            });
        }
    }

    private synchronized void updateData() {
        if (customCandidateAdapter != null) {
            customCandidateAdapter.updateDatas(friendEntities);
        }
        chooseNum.setText(recomendFriend.size() + "/" + friendEntities.size());
        if (friendEntities.size() == 0) {
            view_no_friend.setVisibility(View.VISIBLE);
        } else {
            view_no_friend.setVisibility(View.INVISIBLE);
        }
        if (friendEntities.size() < 4) {
            Toast.makeText(this, "好友人数少于4人，请先添加好友", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.confirm_candidate:
                if (contactsFlag && recommendFlag && qyqFriendFlag) {
                    presenter.loadCondidateFriends(selectFriend);
                } else {
                    Toast.makeText(this, "正在加载好友，请稍后！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.text_cancel_query:
                view_search.setVisibility(View.GONE);
                edittext_input_query.setText("");
                toolsView.setVisibility(View.VISIBLE);
                cancelQuery();
                break;
            case R.id.image_search:
                if (toolsView.isShown()) {
                    toolsView.setVisibility(View.GONE);
                    view_search.setVisibility(View.VISIBLE);
                    SystemUtils.openInputMethod(this, image_search);
                }
                break;
        }
    }

    @Override
    public Loader<List<ContactsInfoEntity>> onCreateLoader(int id, Bundle args) {
        return createContacts();
    }

    @Override
    public void onLoadFinished(Loader<List<ContactsInfoEntity>> loader, List<ContactsInfoEntity> data) {
        getSupportLoaderManager().destroyLoader(LoadContactsAsync.ASYNC_ID);
        contactsInfoEntities.clear();
        contactsInfoEntities.addAll(data);
        contactsFlag = true;
        loadFriends();
    }

    @Override
    public void onLoaderReset(Loader<List<ContactsInfoEntity>> loader) {

    }


    @Override
    public void updateFriendListView(List<MineFriendEntity> friendListEntity) {//后台返回的好友列表
        qyqFriendFlag = true;
        if (friendListEntity != null) {
            qyqFriend.clear();
            qyqFriend.addAll(friendListEntity);
        }
        loadFriends();
    }

    @Override
    public void updateCandidate(List<MineFriendEntity> candidateEntity) {//候选人列表
        recommendFlag = true;
        if (candidateEntity != null && candidateEntity.size() > 0) {
            for (MineFriendEntity friendEntity : candidateEntity) {
                friendEntity.isRecomend = true;
            }
            recomendFriend.clear();
            recomendFriend.addAll(candidateEntity);
            selectFriend.addAll(candidateEntity);
        }
        loadFriends();
    }

    @Override
    public void updateSetCandidateView(CommonEntity commonEntity) {
        //提交设置候选人
        Toast.makeText(this, "设置成功！", Toast.LENGTH_SHORT).show();
//        recomendFriend.clear();
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        this.finish();
    }
}
